package com.situ.web.servlet;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/download")
public class DownloadServlet extends HttpServlet{
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String fileName = req.getParameter("fileName");
		String filePath = getServletContext().getRealPath("/download/" + fileName);
		
		String mimeType = getServletContext().getMimeType(fileName);
		System.out.println(mimeType);
		resp.setContentType(mimeType);
		// 设置响应头，告诉浏览器以附件形式下载，而不是解析展示
		resp.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
		
		InputStream inputStream = new FileInputStream(filePath);
		// 获取输出流：通过Response获得输出流，用于向客户端浏览器输出
		OutputStream outputStream = resp.getOutputStream();
		byte[] buffer = new byte[1024];
		int length = 0;
		while((length = inputStream.read(buffer)) != -1) {
			outputStream.write(buffer, 0, length);
		}
		outputStream.close();
		inputStream.close();
		
	}
}
